package com.webchat.thread;

import com.webchat.Utils.HibernateUtil;
import com.webchat.Utils.SessionUtils;
import com.webchat.controller.WebsocketController;
import com.webchat.model.UsersEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Transaction;

import javax.websocket.Session;
import java.util.Map;

/**
 * Created by YongX on 2016/8/20.
 */
public class UserOnlineHandleThread extends Thread {
    private static Log logger = LogFactory.getLog(UserOnlineHandleThread.class);
    @Override
    public void run() {
        super.run();
        while (true){
            try {
                sleep(10000);
                Map<Integer, Session> map = SessionUtils.clients;
                for (Map.Entry<Integer, Session> entry : map.entrySet()) {
                    setUserOnlineTime(entry.getKey());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void setUserOnlineTime(Integer uid){
        org.hibernate.Session hbsession = HibernateUtil.getSessionFactory().openSession();
        Transaction ts = hbsession.beginTransaction();
        Integer time =  Integer.parseInt((System.currentTimeMillis() / 1000 +25)+"");
        UsersEntity users = hbsession.get(UsersEntity.class, uid);
        users.setOnlineTime(time.toString());
        hbsession.update(users);
        ts.commit();
        hbsession.close();
    }
}
